package cn.ffcs.uec.outStaffBatchImportApply.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffBatchImportApply.action.bean.OutStaffTalentApprovalViewMainBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecTalentTeamManager;
import cn.ffcs.uec.staff.model.UecTalentTeam;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;

/**
 * 专业人才队伍批量导入审批
 * 
 * @author liuxiaodong
 *
 */
@Controller
@Scope("prototype")
public class OutStaffTalentApprovalViewMainComposer extends BasePortletComposer {

	private static final long serialVersionUID = -1763827601951112531L;

	private OutStaffTalentApprovalViewMainBean bean = new OutStaffTalentApprovalViewMainBean();

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");

	private UecTalentTeamManager uecTalentTeamManager = (UecTalentTeamManager) ApplicationContextUtil
			.getBean("uecTalentTeamManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	/**
	 * 外包人员基本信息
	 */
	private UecOutStaffInfo outStaffInfo = UecOutStaffInfo.newInstance();

	private UecTalentTeam uecTalentTeam = UecTalentTeam.newInstance();

	private String taskDefKey;

	private String opType;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);

	}

	/**
	 * 界面初始化
	 */
	public void onCreate$outStaffTalentApprovalViewMainWin() {
		bandListbox();
		bindBean();
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {
		// 非查看历史工单
		if (!ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 添加校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	public void postApprovalData() throws InterruptedException {
		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}

		PubUtil.fillPoFromEditorBean(uecTalentTeam, bean);
		// 开始时间
		uecTalentTeam.setBegindate(DateUtil.dateToStr(bean.getBegindate()
				.getValue()));
		// 结束时间
		uecTalentTeam.setEnddate(DateUtil.dateToStr(bean.getEnddate()
				.getValue()));
		// 退出时间
		uecTalentTeam.setGlbdef14(DateUtil.dateToStr(bean.getGlbdef14()
				.getValue()));
		uecTalentTeam.setModifiedtime(DateUtil.getCurrenDate());
		uecTalentTeam.setModifier(currentName);
		DefaultDaoFactory.getDefaultDao().updateObject(uecTalentTeam);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);

	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});
	}

	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();

	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭弹窗
	 */
	public void onCancel() {
		this.bean.getOutStaffTalentApprovalViewMainWin().onClose();
	}

	/**
	 * 获取传值
	 * 
	 * @throws ParseException
	 * @throws WrongValueException
	 */
	private void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getOutStaffTalentApprovalViewMainWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		opType = (String) arg.get("opType");
		if (ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {

			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		if (null != oaBaseObject) {
			// 2.获取人员信息
			String outStaffIdHis = oaBaseObject.getOutStaffIdHis();
			outStaffInfo.setOutStaffId(Long.parseLong(outStaffIdHis));
			outStaffInfo = uecOutStaffManager
					.findUecOutStaffInfoByOutStaffId(outStaffInfo);
			if (null != outStaffInfo) {
				PubUtil.fillBeanFromPo(outStaffInfo, bean);
				UecOrgOrgs newOrgOrgs = UecOrgOrgs.newInstance();
				newOrgOrgs.setPkOrg(outStaffInfo.getPkHrorg());
				newOrgOrgs = uecOrgOrgsManager
						.findUecOrgOrgsByUecOrgOrgs(newOrgOrgs);
				if (null != newOrgOrgs) {
					bean.getUecOrgName().setValue(newOrgOrgs.getName());
				}

			}
			// 获取审批中专业人才队伍信息
			String talentTeamId = oaBaseObject.getTalentTeamId();
			uecTalentTeam.setTalentTeamId(Long.valueOf(talentTeamId));
			uecTalentTeam = uecTalentTeamManager
					.findUecTalentTeamById(uecTalentTeam);
			PubUtil.fillBeanFromPo(uecTalentTeam, bean);
			// 开始时间
			bean.getBegindate().setValue(
					DateUtil.patternStrToDate(uecTalentTeam.getBegindate()));
			// 结束时间
			bean.getEnddate().setValue(
					DateUtil.patternStrToDate(uecTalentTeam.getEnddate()));
			// 退出时间
			bean.getGlbdef14().setValue(
					DateUtil.patternStrToDate(uecTalentTeam.getGlbdef14()));
		}

	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canReject
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	private void bandListbox() {
		// 专业人才名称glbdef1
		ListboxUtils.rendererForEdit(bean.getGlbdef1(),
				NodeVoUtil.getDictionaries(UecConstants.PROFESSIONAL_NAME));
		// 专业人才等级glbdef2
		ListboxUtils.rendererForEdit(bean.getGlbdef2(),
				NodeVoUtil.getDictionaries(UecConstants.PROFESSIONAL_LEVEL));
		// 子专业：申报专业-电信 glbdef9
		ListboxUtils
				.rendererForEdit(bean.getGlbdef9(), NodeVoUtil
						.getDictionaries(UecConstants.PROFESSIONAL_SUB_MAJOR));
		// 年度考核结果 glbdef3
		ListboxUtils.rendererForEdit(bean.getGlbdef3(), NodeVoUtil
				.getDictionaries(UecConstants.PROFESSIONAL_EXAM_RESULT));
		// 聘任状态 glbdef13
		ListboxUtils.rendererForEdit(bean.getGlbdef13(),
				NodeVoUtil.getDictionaries(UecConstants.EMP_STATUS));

		// 人才类型
		List<NodeVo> nodeVoGlbdef10List = new ArrayList<NodeVo>();
		String[][] glbdef10 = { { "1", "实操" }, { "2", "非实操" }, { "", "无" } };
		for (int i = 0; i < glbdef10.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(glbdef10[i][j]);
				nodeVo.setName(glbdef10[i][j + 1]);
			}
			nodeVoGlbdef10List.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getGlbdef10(), nodeVoGlbdef10List);

		// 绑定是否生效
		List<NodeVo> nodeVoGlbdef8 = new ArrayList<NodeVo>();
		String[][] glbdef8 = { { "Y", "是" }, { "N", "否" } };
		for (int i = 0; i < glbdef8.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(glbdef8[i][j]);
				nodeVo.setName(glbdef8[i][j + 1]);
			}
			nodeVoGlbdef8.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getGlbdef8(), nodeVoGlbdef8);

	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getSelectedItem()
				.getValue())) {
			return "请选择专业人才名称";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef2().getSelectedItem()
				.getValue())) {
			return "请选择专业人才等级";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef3().getSelectedItem()
				.getValue())) {
			return "请选择年度考核结果";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef4().getValue())) {
			return "请填写专家津贴金额";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef6().getValue())) {
			return "请填写股票增值权";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef10().getSelectedItem()
				.getValue())) {
			return "请选择人才类型";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef11().getValue())) {
			return "请填写第一年考核";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef12().getValue())) {
			return "请填写第二年考核";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef13().getSelectedItem()
				.getValue())) {
			return "请选择聘任状态";
		} else if (StrUtil.isNullOrEmpty(bean.getGlbdef9().getSelectedItem()
				.getValue())) {
			return "请填写子专业";
		} else if (StrUtil.isNullOrEmpty(bean.getBegindate().getValue())) {
			return "请选择开始日期";
		}
		return null;
	}

}
